"use client"

import type React from "react"
import { useState, useCallback, memo } from "react"
import { Modal, Upload, Button, Input, Form, message, Space, Select, Typography } from "antd"
import { UploadOutlined, DownloadOutlined, ImportOutlined, ExportOutlined } from "@ant-design/icons"
import type { UploadProps } from "antd"
import type { Host } from "../types"
import type { InputChangeEvent, FileReaderResult } from "../types/common"
import axios from "axios"

const { TextArea } = Input
const { Text } = Typography

interface ImportExportProps {
  categories: string[]
  onImportSuccess: () => void
}

interface ImportFormValues {
  category: string
  content: string
}

interface ExportFormValues {
  category?: string
}

export const ImportExport: React.FC<ImportExportProps> = memo(({ categories, onImportSuccess }) => {
  const [importModalVisible, setImportModalVisible] = useState(false)
  const [exportModalVisible, setExportModalVisible] = useState(false)
  const [importForm] = Form.useForm<ImportFormValues>()
  const [exportForm] = Form.useForm<ExportFormValues>()
  const [importContent, setImportContent] = useState("")
  const [exportContent, setExportContent] = useState("")

  const handleImport = useCallback(
    async (values: ImportFormValues) => {
      try {
        const { data } = await axios.post<Host[]>("http://localhost:3001/api/import", {
          content: importContent,
          category: values.category,
        })

        message.success(`成功导入 ${data.length} 条记录`)
        setImportModalVisible(false)
        importForm.resetFields()
        setImportContent("")
        onImportSuccess()
      } catch (error) {
        message.error("导入失败")
      }
    },
    [importContent, importForm, onImportSuccess],
  )

  const handleExport = useCallback(async (values: ExportFormValues) => {
    try {
      const { data } = await axios.get<{ content: string }>("http://localhost:3001/api/export", {
        params: {
          category: values.category,
        },
      })

      setExportContent(data.content)
    } catch (error) {
      message.error("导出失败")
    }
  }, [])

  const uploadProps: UploadProps = {
    accept: ".txt,.hosts",
    beforeUpload: (file) => {
      const reader = new FileReader()
      reader.onload = (e: ProgressEvent<FileReaderResult>) => {
        if (e.target?.result) {
          setImportContent(e.target.result)
        }
      }
      reader.readAsText(file)
      return false
    },
    maxCount: 1,
  }

  const handleContentChange = useCallback((e: InputChangeEvent) => {
    setImportContent(e.target.value)
  }, [])

  const downloadHostsFile = useCallback(() => {
    const blob = new Blob([exportContent], { type: "text/plain" })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    a.download = "hosts"
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)
  }, [exportContent])

  const resetImportModal = useCallback(() => {
    setImportModalVisible(false)
    importForm.resetFields()
    setImportContent("")
  }, [importForm])

  const resetExportModal = useCallback(() => {
    setExportModalVisible(false)
    exportForm.resetFields()
    setExportContent("")
  }, [exportForm])

  return (
    <>
      <Space>
        <Button icon={<ImportOutlined />} onClick={() => setImportModalVisible(true)}>
          导入
        </Button>
        <Button icon={<ExportOutlined />} onClick={() => setExportModalVisible(true)}>
          导出
        </Button>
      </Space>

      {/* 导入对话框 */}
      <Modal title="导入 Hosts" open={importModalVisible} onCancel={resetImportModal} footer={null}>
        <Form form={importForm} onFinish={handleImport} layout="vertical">
          <Form.Item name="category" label="分类" rules={[{ required: true, message: "请选择或输入分类" }]}>
            <Select showSearch allowClear placeholder="选择或输入分类">
              {categories.map((category) => (
                <Select.Option key={category} value={category}>
                  {category}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label="选择文件">
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>选择 Hosts 文件</Button>
            </Upload>
          </Form.Item>

          <Form.Item label="或直接粘贴内容">
            <TextArea
              rows={10}
              value={importContent}
              onChange={handleContentChange}
              placeholder="# 在此粘贴 hosts 文件内容..."
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                导入
              </Button>
              <Button onClick={resetImportModal}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 导出对话框 */}
      <Modal title="导出 Hosts" open={exportModalVisible} onCancel={resetExportModal} footer={null}>
        <Form form={exportForm} onFinish={handleExport} layout="vertical">
          <Form.Item name="category" label="分类">
            <Select showSearch allowClear placeholder="选择分类（不选则导出全部）">
              {categories.map((category) => (
                <Select.Option key={category} value={category}>
                  {category}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              生成内容
            </Button>
          </Form.Item>

          {exportContent && (
            <>
              <Form.Item label="导出内容">
                <TextArea rows={10} value={exportContent} readOnly />
              </Form.Item>

              <Form.Item>
                <Space>
                  <Button type="primary" icon={<DownloadOutlined />} onClick={downloadHostsFile}>
                    下载文件
                  </Button>
                  <Button onClick={resetExportModal}>关闭</Button>
                </Space>
              </Form.Item>
            </>
          )}
        </Form>
      </Modal>
    </>
  )
})
